package org.hamster.multidropbox.dropbox.model
{
	import mx.collections.ArrayCollection;
	import mx.rpc.Fault;
	
	import org.hamster.multidropbox.dropbox.event.AppDropboxEvent;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxClient;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxLinkFolderItemVO;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxLinkFoldersVO;
	import org.hamster.multidropbox.main.model.AppStorageProxy;
	import org.hamster.multidropbox.main.utils.PureMVCHelper;
	
	public class DropboxStorageProxy extends AppStorageProxy
	{
		public static const NAME:String = "org.hamster.multidropbox.dropbox.model.DropboxStorageProxy";
		
		public function DropboxStorageProxy()
		{
			super(NAME, "");
		}
		
		public function loadDropboxStorage():void
		{
			super.loadData("dropbox-client.xml");
		}
		
		public function saveDropboxStorage():void
		{
			var clientList:ArrayCollection = PureMVCHelper.dropboxClientListProxy.dropboxClientList;
			var linkedList:ArrayCollection = PureMVCHelper.dropboxLinkFoldersProxy.dropboxLinkFoldersList;
			var dataCollection:ArrayCollection = new ArrayCollection();
			dataCollection.addAll(clientList);
			dataCollection.addAll(linkedList);
			super.saveData(dataCollection, "dropbox-client.xml");
			this.sendNotification(AppDropboxEvent.DROPBOX_STORAGE_SAVE_RESULT);
		}
		
		override protected function processResultHandler(data:Object):void
		{
			var rootXML:XML = data as XML;
			PureMVCHelper.dropboxClientListProxy.dropboxClientList.removeAll();
			var clientXMLList:XMLList = rootXML.child('client');
			for each (var clientXML:XML in clientXMLList) {
				var clientVO:AppDropboxClient = PureMVCHelper.dropboxClientListProxy.genClient();
				clientVO.decodeXML(clientXML);
				PureMVCHelper.dropboxClientListProxy.dropboxClientList.addItem(clientVO);
			}
			
			PureMVCHelper.dropboxLinkFoldersProxy.dropboxLinkFoldersList.removeAll();
			var linkXMLList:XMLList = rootXML.child('link-folder');
			for each (var linkXML:XML in linkXMLList) {
				var linkVO:AppDropboxLinkFoldersVO = new AppDropboxLinkFoldersVO();
				linkVO.decodeXML(linkXML);
				PureMVCHelper.dropboxLinkFoldersProxy.dropboxLinkFoldersList.addItem(linkVO);
			}
			
			this.sendNotification(AppDropboxEvent.DROPBOX_STORAGE_LOAD_RESULT, PureMVCHelper.dropboxClientListProxy.dropboxClientList);
		}
		
		override protected function processFaultHandler(fault:Fault):void
		{
			this.sendNotification(AppDropboxEvent.DROPBOX_STORAGE_LOAD_FAULT);
		}
	}
}